// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/expression/vector_function.h>

namespace kumo::pollux::functions {
    namespace {
        class ToUtf8Function : public exec::VectorFunction {
        public:
            void apply(
                const SelectivityVector &rows,
                std::vector<VectorPtr> &args,
                const TypePtr & /* outputType */,
                exec::EvalCtx &context,
                VectorPtr &result) const override {
                VectorPtr localResult;

                // Input can be constant or flat.
                const auto &arg = args[0];
                if (arg->is_constant_encoding()) {
                    auto value = arg->as<ConstantVector<StringView> >()->value_at(0);
                    localResult = std::make_shared<ConstantVector<StringView> >(
                        context.pool(), rows.end(), false, VARBINARY(), std::move(value));
                } else {
                    auto flatInput = arg->as_flat_vector<StringView>();

                    auto stringBuffers = flatInput->stringBuffers();
                    POLLUX_CHECK_LE(rows.end(), flatInput->size());
                    localResult = std::make_shared<FlatVector<StringView> >(
                        context.pool(),
                        VARBINARY(),
                        nullptr,
                        rows.end(),
                        flatInput->values(),
                        std::move(stringBuffers));
                }

                context.moveOrCopyResult(localResult, rows, result);
            }

            static std::vector<std::shared_ptr<exec::FunctionSignature> > signatures() {
                // varchar -> varbinary
                return {
                    exec::FunctionSignatureBuilder()
                    .returnType("varbinary")
                    .argumentType("varchar")
                    .build()
                };
            }
        };
    } // namespace

    POLLUX_DECLARE_VECTOR_FUNCTION(
        udf_to_utf8,
        ToUtf8Function::signatures(),
        std::make_unique<ToUtf8Function>());
} // namespace kumo::pollux::functions
